﻿#ifndef Time_h__2013_10_18__13_41
#define Time_h__2013_10_18__13_41

#include "df_macro.h"

namespace df
{
#include <time.h>
	using namespace sdf;

	struct Time
	{
		const static time_t time_of_day = 24 * 60 * 60;

		int16_t year_ = 0;
		int8_t month_ = 0;
		int8_t day_ = 0;

		int8_t dayOfWeek_ = 0;
		int8_t hour_ = 0;
		int8_t minute_ = 0;
		int8_t second_ = 0;



		//获取当前时间
		Time & Now()
		{
			secondToTime(getNow(), *this);
			return *this;
		}

		//计算准确时间(例如:2014-1-32计算结果:2014-2-1)
		Time & Init()
		{
			secondToTime(timeToSecond(*this), *this);
			return *this;
		}

		Time & FromUnix(time_t t)
		{
			secondToTime(t, *this);
			return *this;
		}

		//计算两个时间戳之间相差的天数
		static time_t getDays(time_t start, time_t end){
			return std::abs(start / time_of_day - end / time_of_day);
		}


		//将UNIX时间戳转换为Time
		static void secondToTime(time_t t, Time & time)
		{
			struct tm *p;
			p = localtime(&t); /*取得当地时间*/
			time.year_ = (int16_t)(1900 + p->tm_year);
			time.month_ = (int8_t)p->tm_mon + 1;
			time.day_ = (int8_t)p->tm_mday;

			time.dayOfWeek_ = (int8_t)p->tm_wday;
			if (time.dayOfWeek_ == 0)
				time.dayOfWeek_ = 7;
			time.hour_ = (int8_t)p->tm_hour;
			time.minute_ = (int8_t)p->tm_min;
			time.second_ = (int8_t)p->tm_sec;
		}




		time_t toUNIX(){
			return timeToSecond(*this);
		}
		
		//将Time转换为unix时间戳
		static time_t timeToSecond(const Time & time)
		{
			struct tm p = { 0 };
			p.tm_year = time.year_ - 1900;
			p.tm_mon = time.month_ - 1;
			p.tm_mday = time.day_;

			p.tm_wday = time.dayOfWeek_;

			if (p.tm_wday == 7)
				p.tm_wday = 0;
			p.tm_hour = time.hour_;
			p.tm_min = time.minute_;
			p.tm_sec = time.second_;
			return mktime(&p);
		}

		//获取UNIX时间戳(1900年到现在的秒数)
		static time_t getNow()
		{
			time_t timep;
			time(&timep);
			return timep;
		}


		String & ToString(String & str)
		{
			str << year_ << _T('-') << month_ << _T('-') << day_ << _T(' ');

			if (hour_ < 10)
				str << _T('0');

			str << hour_ << _T(':');

			if (minute_ < 10)
				str << _T('0');

			str << minute_ << _T(':');

			if (second_ < 10)
				str << _T('0');

			str << second_;
			return str;
		}

		String ToString()
		{
			String time;
			ToString(time);
			return time;
		}

#ifdef WIN32
		static String & FileTimeToStr(FILETIME & fTime, String & str)
		{
			FILETIME ftLocal;
			//系统时间结构
			SYSTEMTIME st;
			//调整为系统所在时区的时间
			FileTimeToLocalFileTime(&fTime, &ftLocal);
			//将文件时间转换为SYSTEMTIME格式，便于显示
			FileTimeToSystemTime(&ftLocal, &st);
			str << st.wYear << _T('-') << st.wMonth << _T('-') << st.wDay << _T(' ') << st.wHour << _T(':') << st.wMinute << _T(':') << st.wSecond;
			return str;
		}
#endif
	};


}

#endif // Time_h__2013_10_18__13_41
